import React, { useEffect, useState, useImperativeHandle, forwardRef, useContext } from 'react';
import { Button, Space, Table, Tooltip } from 'antd';
import { NumberOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import { fetchExtractColumns } from '@/service/api';
import DatabaseContext from './data-source/database-context';

interface ColumnListProps {
  table: Bn.Meta.MetaTable | undefined;
}

export interface ColumnListRef {
  getColumns: () => Bn.Meta.MetaColumn[] | undefined;
}

const ColumnList = forwardRef(({ table }: ColumnListProps, ref: React.Ref<ColumnListRef>) => {
  const selectedColumns = useRef<Bn.Meta.MetaColumn[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [data, setData] = useState<Bn.Meta.MetaColumn[]>();
  const currentDatabase = useContext(DatabaseContext);
  const columns: TableProps<Bn.Meta.MetaColumn>['columns'] = [
    {
      title: '字段名称',
      dataIndex: 'columnName',
      key: 'columnName'
    },
    {
      title: '字段类型',
      dataIndex: 'columnType',
      key: 'columnType',
      render: (value: string) => {
        let icon = null;
        if (value.toLowerCase().includes('int')) {
          icon = <SvgIcon icon='fluent:number-symbol-32-regular' style={{fontSize: 14,color: '#04b49c'}} />;
        }
        else if (value.toLowerCase().includes('char')) {
          icon = <SvgIcon icon='fluent:text-16-regular' style={{fontSize: 14,color: "#3370ff"}} />;
        }
        else if (value.toLowerCase().includes('date')) {
          icon = <SvgIcon icon='fluent:clock-24-regular' style={{fontSize: 14,color: "#d4380d"}} />;
        }
        else if (value.toLowerCase() == 'decimal') {
          icon = <SvgIcon icon='f7:money-yen' style={{fontSize: 14, color: "#d46b08"}} />;
        }
        return <> {icon} {value} </>
      }
    },
    {
      title: '主键',
      dataIndex: 'isPk',
      key: 'isPk',
      render: (value) => {
        return <>{value ? "PK": ""}</>
      }
    }
  ];

  const rowSelection: TableProps<Bn.Meta.MetaColumn>['rowSelection'] = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[], selectedRows: Bn.Meta.MetaColumn[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
      selectedColumns.current = selectedRows;
    }
  };

  useImperativeHandle(ref, () => ({
    getColumns: () => {
      return selectedColumns.current
    }
  }));

  useEffect(() => {
    (async () => {
      const _columns = (await fetchExtractColumns(currentDatabase.dbName!, table?.tableName!)).data;
      if (_columns) {
        setSelectedRowKeys(_columns?.map(v => v.id));
        setData(_columns);
        selectedColumns.current = _columns;
      }
    })();
  }, [table]);

  return (
    <Table<Bn.Meta.MetaColumn>
      size="small"
      rowKey={'id'}
      pagination={false}
      columns={columns}
      dataSource={data}
      rowSelection={rowSelection}
      scroll={{ y: document.body.clientHeight - 398 }}
    />
  );
});

export default ColumnList;
